#include <iostream>
#include <queue>
#include <cstring>

using namespace std;

const int N = 1010, INF = 0x3f3f3f3f;

typedef pair<int, int> PII;

char a[N][N];
int st[N][N];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};

int n, k;

void bfs()
{
	queue<PII> q;
	q.push({1, 1}); // hp  
	st[1][1] = 0;
	while(q.size())
	{
		auto t = q.front(); q.pop();
		int cx = t.first, cy = t.second;
		for(int k = 0; k < 4; k++)
		{
			int nx = cx + dx[k], ny = cy + dy[k];
			if(nx >= 1 && ny >= 1 && nx <= n && ny <= m)
			{
				if(st[nx][ny] < st[cx][cy] + 1 || a[nx][ny] == '#' || a[nx][ny] == 'X') continue;
				if(a[nx][ny] == '%')
				{
					queue<PII> tmp;
					tmp.push({nx, ny});
					st[nx][ny] = st[cx][cy] + 1;
					for(int p = 1; p <= 3; p++)
					{
						auto _t = tmp.front(); tmp.pop();
							
					}
				}
				else
				{
					st[nx][ny] = st[cx][cy] + 1;
					q.push({nx, ny});
				}

			}
		}
	}
}

int main()
{
	cin >> n >> k;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= m; j++)
		{
			cin >> a[i][j];
		}
	}
	memset(st, 0x3f, sizeof st);
	
	bfs();
	
	if(st[n][n] == INF) cout << -1 << endl;
	else cout << st[n][n] << endl;
	
	return 0;
 } 
